package yanglei.day0109.lottery.utils;

import java.sql.*;

/**
 * @Author: YangLei
 * @CreateTime: 2023-01-07  16:15
 * @Description: TODO
 */
public class BaseDao {
    protected static String driver;
    protected static String url;
    protected static String username;
    protected static String password;

    protected Connection conn;

    protected PreparedStatement pstmt;

    protected ResultSet rs;
    // 1、建立数据库连接
    public Connection getConn(){
        // 获取driver   url     username    password 这四个参数对应值
        driver = ConfigManager.getInstance().getProperty("orcl.driver");
        url = ConfigManager.getInstance().getProperty("orcl.url");
        username = ConfigManager.getInstance().getProperty("orcl.username");
        password = ConfigManager.getInstance().getProperty("orcl.password");

        /*driver = "oracle.jdbc.driver.OracleDriver";
        url = "jdbc:oracle:thin:@localhost:1521:orcl";
        username = "LOTTERY";
        password = "123456";*/
        try {
            // ①加载数据库驱动
            Class.forName(driver);
            // ②建立数据库连接对象
            conn = DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    // 2、关闭数据库所有连接
    public void closeAll(ResultSet rs, PreparedStatement pstmt, Connection conn) {
        try {
            if (rs == null) {
                rs.close();
            }
            if (pstmt == null) {
                pstmt.close();
            }
            if (conn == null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    // 3、定义公共的查询方法
    public ResultSet executeQuery(String sql, Object...params) {
        conn = getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return rs;
    }
    // 4、定义公共的增删改方法
    public int executeUpdate(String sql, Object...params) {
        int result = 0;
        conn = getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i + 1, params[i]);
            }
            result = pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
    public static void main(String[] args) {
        BaseDao bd = new BaseDao();
        System.out.println(bd.getConn());
    }

}
